parser grammar CalculatorParser;

options {
  output = AST;
  tokenVocab = CalculatorLexer;
}

@header{
  package org.concepts.java.antlr.calculator;
}

/*
 * Operator precedence in decreasing order:
 * 
 *  /, *  (/ and * have the same precedence)
 *  +, -  (+ and - have the same precedence)
 *  
 *  Operators with same precedence are processed left to right.
 *  
 *  E.g. 3 + 4 * 5     = 3 + 20 = 23
 *  
 *  Multiply has higher precedence over +, thus we first multiply 4 and 5.
 *  
 *  Arithmitic rule pattern is to first specify the weaker precendence operator
 *  while building the rule top down. E.g.
 *  
 *         +
 *        /   \
 *      3      *
 *            /  \
 *           4    5
 *           
 *  To compute the +, we first need to compute the value of * in above tree.
 *  
 */


expr 
	:	 muldivexpr ((PLS^ | MIN^) muldivexpr)*;


muldivexpr 
	:	 atom ( (MUL^ | DIV^) atom)*;
 
atom   : 
    INT
    |
    LPAREN! expr RPAREN!;
